<<<<<<< HEAD
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::process::{Command, Stdio};
// use std::fs::File;
// use std::io::Write;
// use std::fs::OpenOptions;
use std::fs::{OpenOptions, File};
use std::io::{self, BufRead, BufReader, Write};
use std::{thread, time};

use lazy_static::lazy_static;
use std::sync::Mutex;
// use tokio::time::delay_for;
use std::time::Duration;

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command

use std::collections::VecDeque;
use std::sync::{Arc};
use tauri::{Builder, Window, Manager};

// #[derive(Clone)]
// struct TerminalState {
//     output_buffer: Arc<Mutex<VecDeque<String>>>,
// }



#[tauri::command]
fn add_repl(source: &str, target:&str, target_value:&str, interrupt_target:&str, interrupt_index:&str){
// fn add1_repl(source: &str){
    println!("hhhhhhhh: {}", source);
    println!("eeeeeeee: {}", target);
    println!("wwwwwwww: {}", target_value);
    println!("rrrrrrrr: {}", interrupt_target);
    println!("tttttttt: {}", interrupt_index);
    let mut file = OpenOptions::new().append(true).open("../platforms/stm32f4_user.repl").expect("open error");
    let mut line1 = source.clone().to_string();

    if source == "button"{
        line1.push_str(": Miscellaneous.Button @ ");
        line1.push_str(target);
        line1.push_str(" ");
        line1.push_str(target_value);
        line1.push_str("\n");
        file.write_all(line1.as_bytes()).expect("write error");
        // Ok(());
        let mut line2 = String::from("    ");
        if interrupt_target != "none"{
            line2.push_str("-> ");
            line2.push_str(interrupt_target);
            line2.push_str("@");
            line2.push_str(interrupt_index);
            line2.push_str("\n\n");
        }
        file.write_all(line2.as_bytes()).expect("write error");
    }
    if source == "LED"{
        line1.push_str(": Miscellaneous.LED @ ");
        line1.push_str(target);
        line1.push_str(" ");
        line1.push_str(target_value);
        line1.push_str("\n\n");
        file.write_all(line1.as_bytes()).expect("write error");

        let mut line2 = String::from(target);
        line2.push_str(":\n");
        line2.push_str("    ");
        line2.push_str(target_value);
        line2.push_str(" -> LED@0\n");

        file.write_all(line2.as_bytes()).expect("write error");
    }
}

#[tauri::command]
fn add_resc(name: &str) -> String{
    // 文件路径
    let file_path = "../platforms/stm32f4.resc";
    // 打开文件
    let file = File::open(file_path).expect("open error");
    let reader = BufReader::new(file); 

    let match_string = "macro reset";

    // 创建一个临时文件来保存修改后的内容
    let temp_file_path = "../platforms/stm32f4_temp.resc";
    let mut temp_file = File::create(temp_file_path).expect("create error");

    // 逐行读取文件内容
    for line in reader.lines() {
        let current_line = line.expect("line null");
        
        // 检查当前行是否包含匹配字符串
        if current_line.contains(match_string) {
            // 在匹配字符串之前插入新的字符串
            let mut insert_line = String::new();
            insert_line.push_str("$bin ?= @");
            insert_line.push_str(name);
            writeln!(temp_file, "{}", insert_line).expect("write error");
        }

        // 将当前行写入临时文件
        writeln!(temp_file, "{}", current_line).expect("write error");
    }
    std::fs::rename(temp_file_path, file_path).expect("rename error");
    format!("{}", name)
}

#[tauri::command]
fn start(window: Window){
    // 启动 Renode 进程
    let renode_process = Command::new("renode")
        .arg("-e")
        .arg("start @../platforms/stm32f4.resc")
        .stdout(Stdio::piped())
        .spawn()
        .expect("Failed to start Renode process");
    // 获取 Renode 进程的标准输出
    if let Some(stdout) = renode_process.stdout {
        let output_reader = BufReader::new(stdout);

        // 启动一个线程来读取 Renode 输出并发送到前端
        std::thread::spawn(move || {
            for line in output_reader.lines() {
                if let Ok(line) = line {
                    // 将每行输出发送到前端
                    window.emit_to(
                            "main",
                            "receive_terminal_output",
                            Some(line.clone()),
                        )
                        .unwrap();
                    // window.emit_to(
                    //     "main",
                    //     "receive_terminal_output",
                    //     Some("\n"),
                    // )
                    // .unwrap();
                }
            }
        });
    }
}

fn start_renode() -> String{
    let output = Command::new("renode")
        .arg("-e")
        .arg("start @../platforms/stm32f4.resc")
        .output()
        .map(|output| {
            // 将输出转换为字符串
            String::from_utf8_lossy(&output.stdout).to_string()
        })
        .unwrap_or_else(|err| {
            // 处理执行命令失败的情况
            format!("Error executing command: {}", err)
        });
    output
    // let mut cmd = Command::new("renode");
    // cmd.arg("-e").arg("include @/home/freekeeper/renode/stm32f4.resc");
    // // 延迟 3 秒
    // // thread::sleep(Duration::from_secs(10));

    // // 异步延迟 10 秒
    // // thread::sleep(time::Duration::from_millis(10));

    // cmd.arg("-e").arg("start");
    // match cmd.spawn() {
    //     Ok(mut child) => {
    //         // 处理外部程序的标准输出、标准错误或其他操作
    //         // let status = child.wait().expect("Failed to wait on child");
    //         // println!("Child process exited with: {:?}", status);
    //     }
    //     Err(e) => {
    //         eprintln!("Error: {}", e);
    //     }
    // };
}

fn main(){
    // 第一步：定义repl文件
    let mut file = File::create("../platforms/stm32f4_user.repl").expect("create error");
    file.write_all(b"using \"platforms/cpus/stm32f4.repl\" \n\n").expect("write error");

    // 第二步：定义resc文件
    // 第三步：启动renode
    // tauri::Builder::default()
    //     .manage(TerminalState { output_buffer: output_buffer.clone() })
    //     .invoke_handler(tauri::generate_handler![add_repl, add_resc, start, send_terminal_input])
    //     .run(tauri::generate_context!())
    //     .expect("error while running tauri application");

    Builder::new()
        // .manage(TerminalState { output_buffer: output_buffer.clone() })
        .invoke_handler(tauri::generate_handler![add_repl, add_resc, start])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
=======
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

fn main() {
    app_lib::run();
>>>>>>> v3.0
}
